package com.winai.launcher.override;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.ks.projectbasictools.base_interface.StringCallBack;
import com.ks.projectbasictools.okhttp.StringCallbackYu;
import com.ks.projectbasictools.utils.JSONUtil;
import com.ks.projectbasictools.utils.LogUtils;
import com.ks.projectbasictools.utils.ToastKs;
import com.ks.projectbasictools.utils.ToastUtil;
import com.winai.launcher.base.BaseEntity;

import okhttp3.Call;

/**
 * 作者：康少
 * 时间：2019/12/23 0023
 * 说明：请求回调预加载
 */
public class StringCallBackYu<T extends BaseEntity> extends StringCallbackYu {

    @Override
    public void onResponse(Context mContext, String response, int id, StringCallBack mStringCallBack, String requestType) {
        if (LogUtils.isDebug)
            LogUtils.d(requestType + "访问response:" + JSONUtil.formatJSONString(response));
        Gson gson = new Gson();
        try {
            T t = gson.fromJson(response, mStringCallBack.getType());
            if (authResponse(t)) {
                mStringCallBack.onResponse(t, id);
            } else {
                ToastUtil.show(mContext, "错误码：" + t.getCode() + "；错误信息：" + t.getMesg());
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

    @Override
    public void onError(Context mContext, Call call, Exception e, int id, StringCallBack mStringCallBack, String requestType) {
        if (LogUtils.isDebug)
            LogUtils.d(requestType + "访问ErrorMessage:" + e.getMessage());
        if (e.getMessage() != null && e.getMessage().equals("timeout")) {
            ToastKs.show(mContext, "网络走丢了，请稍后再试");
        } else {
            ToastUtil.show(mContext, "error:" + e.getMessage());
        }
        mStringCallBack.onError(call, e, id);
    }

    private boolean authResponse(BaseEntity entity) {
        return TextUtils.isEmpty(entity.getCode()) || entity.getCode().equals("000000") || entity.getCode().equals("0");
    }

}
